import os
from typing import Dict, Optional
from dotenv import load_dotenv

class ConfigManager:
    def __init__(self, category_config_path: str, api_key: Optional[str] = None, base_url: Optional[str] = None):
        self.category_config_path = category_config_path
        self._api_key = api_key
        self._base_url = base_url
        load_dotenv()

    def load_category_config(self) -> Dict:
        """解析类目表配置文件为字典结构。"""
        with open(self.category_config_path, 'r', encoding='utf-8') as f:
            content = f.read()
        categories = {}
        current_category = None
        last_option = None
        for raw in content.split('\n'):
            line = raw.strip()
            if not line:
                continue
            if line.startswith('()'):
                current_category = line.split('/')[0].replace('()', '').strip()
                categories[current_category] = {}
                last_option = None
            elif line.endswith('/#选项#/'):
                option = line.split('/')[0].strip()
                categories[current_category][option] = []
                last_option = option
            elif line.startswith('<关键词=') and current_category and last_option:
                keywords = line.replace('<关键词=', '').replace('>', '')
                keywords_list = [kw.strip() for kw in keywords.split(' OR ')]
                categories[current_category][last_option] = keywords_list
        return categories

    def get_api_key(self) -> str:
        """返回 API Key：优先使用入参，其次读取环境变量 ZHIPU_API_KEY。"""
        api_key = self._api_key or os.getenv('ZHIPU_API_KEY')
        if not api_key:
            raise RuntimeError('未找到智谱 API Key，请传入或设置环境变量 ZHIPU_API_KEY')
        return api_key

    def get_base_url(self) -> Optional[str]:
        """返回可选的 Base URL（支持 .env 中 GLM_BASE_URL 或 ZHIPU_BASE_URL）。"""
        return self._base_url or os.getenv('GLM_BASE_URL') or os.getenv('ZHIPU_BASE_URL')
